package com.mh.controller;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.mh.common.ChatSessionManager;
import com.mh.dto.vo.AiQuestionVo;
import com.mh.dto.vo.R;
import com.mh.utils.AIUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


/**
 * AI相关接口
 * 
 * @author zmh
 * @since 2025/2/28
 */
@RestController
@CrossOrigin
@RequestMapping("/ai")
@Slf4j
@RequiredArgsConstructor
public class AiController {

    private final AIUtils aiUtils;

    // 用户管理器
    private final ChatSessionManager sessionManager;

    /**
     * 初始化用户聊天会话：将系统prompt给到AI
     * @param openId 用户openId
     * @return 初始化状态
     */
    @GetMapping("/start/{openId}")
    public R<Boolean> startChatSession(@PathVariable("openId") String openId) {
        log.info("用户{}开始聊天", openId);
        return R.success(sessionManager.createSession(openId));
    }

    /**
     * AI聊天接口
     * @param aiQuestionVo 用户问题
     * @return AI响应
     */
    @PostMapping("/send")
    public ResponseEntity<String> chat(@RequestBody AiQuestionVo aiQuestionVo) {
        log.info("收到用户{}问题: {}", aiQuestionVo.getOpenId(), aiQuestionVo.getQuestion());
        try {
            GenerationResult result = aiUtils.continuousChat(aiQuestionVo.getOpenId(), aiQuestionVo.getQuestion());
            log.info("AI响应: {}", result.getOutput());
            String response = result.getOutput().getChoices().get(0).getMessage().getContent();
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("对话异常: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("服务异常: " + e.getMessage());
        }
    }
}
